import useMyFetch from "@/utils/fetch";
import { UseFetchOptions } from "@vueuse/core";
import { ref, Ref } from "vue";

type TReturn<TData> = ReturnType<typeof useMyFetch<TData>> & {
  run: (data?: any) => void;
  refresh: () => void;
  lastParams: Ref<any>;
};

const useRequest = <TData = any>(
  url: string | Ref<string>,
  {
    defaultParams,
    ...restOptions
  }: UseFetchOptions & { defaultParams?: Record<string, any> } = {}
) => {
  const lastParams = ref(defaultParams);

  const { post, data, execute, ...rest } = useMyFetch<TData>(url, {
    method: "POST",
    ...restOptions,
  }).json();

  post(defaultParams);

  // 主动请求方法
  const run = (data?: any) => {
    lastParams.value = data;
    post(data);
    execute();
  };

  // 刷新
  const refresh = () => run(lastParams.value);

  return {
    ...rest,
    lastParams,
    data,
    run,
    refresh,
  } as TReturn<TData>;
};

export default useRequest;
